package com.cjm.algorithm.quick;

import java.util.Arrays;

public class MergeSortCopy1 {
    public static void sort(int[] arr) {
        sort(arr, 0, arr.length - 1);
    }

    public static void sort(int[] arr, int left, int right) {
        if (left >= right) return;
        int mid = (right - left) / 2 + left;
        sort(arr, left, mid);
        sort(arr, mid + 1, right);
        if (arr[mid] > arr[mid + 1]) {
            merge(arr, left, mid, right);
        }
    }

    private static void merge(int[] arr, int left, int mid, int right) {
        int[] aux = Arrays.copyOfRange(arr, left, right + 1);
        int i = left, j = mid + 1;
        for (int k = left; k <= right; k++) {
           if (i > mid) {
               arr[k] = aux[j - left];
               j++;
           } else if (j > right) {
               arr[k] = aux[i - left];
               i++;
           } else if (arr[i-left] < arr[j - left]) {
               arr[k] = aux[i - left];
               i++;
           } else {
               arr[k] = aux[j - left];
               j++;
           }
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[] {4, 6, 2, 8, 4, 1, 5, 7, 96};
        sort(arr);
        for (int i : arr) {
            System.err.println(i);
        }
    }
}
